#这里只管merge并存放到backup文件夹中，删除原文件的操作由其他脚本来完成
import sys
import shutil
import os
import time


def merge_files(file_names, output_file_name):
    """
    Merge files into one file.
    """
    output_file = open(output_file_name, 'w+')
    for file_name in file_names:
        output_file.write(read_file(file_name))
    output_file.close()


def read_file(file_name):
    """
    Read file and return content.
    """
    with open(file_name, 'r') as f:
        return f.read()


def get_date():
    return os.stat(sys.argv[0]).st_mtime


def rename_file(file_name):
    """
    Rename file with date when file created.
    """
    new_name = get_date_str(get_date()) + '-' + file_name
    #os.rename(file_name, new_name)
    if not os.path.exists('./backup'):
        os.mkdir('./backup')
    shutil.move(file_name, './backup/' +new_name)

def get_date_str(date):
    return time.strftime('%Y-%m-%d-%H-%M', time.localtime(date))


if __name__ == '__main__':
    # get all the file names in the current directory with the extension .config
    file_names = [file_name for file_name in os.listdir(
        '.') if file_name.endswith('.config')]
    merge_files(file_names, 'version.txt')
    rename_file("version.txt")

